<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>引出生命周期</title>
		<!-- 引入react核心库 -->
		<script type="text/javascript" src="../js/react.development.js"></script>
		<!-- 引入react-dom，用于支持react操作DOM -->
		<script type="text/javascript" src="../js/react-dom.development.js"></script>
		<!-- 引入babel，用于解析jsx为js -->
		<script type="text/javascript" src="../js/babel.min.js"></script>
	</head>
	<body>
		<!-- 准备好一个容器 -->
		<div id="test"></div>

		<script type="text/babel">
			//定义组件
			class Demo extends React.Component{
				state = {opacity:1} //初始化状态

				render(){
					console.log('---render---')
					//从state中获取透明度
					const {opacity} = this.state
					return (
						<div>
							<h2 style={{opacity}}>分手了，怎么办？</h2>
							<button onClick={this.death}>不活了</button>
						</div>
					)
				}
				
				//组件完成挂载 ---- 只是在组件挂载完毕后执行一次
				componentDidMount(){
					console.log('---componentDidMount---')
					//开启定时器，更新透明度
					this.timer = setInterval(() => {
						let {opacity} = this.state //获取原来的透明度 
						opacity -= 0.1 //透明度减小
						if(opacity <= 0) opacity = 1 //重置透明度
						this.setState({opacity}) //更新state
					},200);
				}
				
				//组件将要卸载 ---- 只是在组件将要卸载时执行一次
				componentWillUnmount(){
					console.log('---componentWillUnmount---')
					clearInterval(this.timer)
				}

				//“不活了”按钮的回调
				death = ()=>{
					//卸载组件
					ReactDOM.unmountComponentAtNode(document.getElementById('test'))
				}
			}

			//渲染组件
			ReactDOM.render(<Demo/>,document.getElementById('test'))
		</script>
	</body>
</html>